#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/07/20
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

import os
from time import sleep
from datetime import datetime
from random import choice
from threading import Thread
from queue import Queue
from project.define import create_logger


# 识别队列
CameraQ = Queue()


class CameraService:
    def __init__(self, **kwargs) -> None:
        self.CameraID = kwargs.get('CameraID')
        self.GateID = kwargs.get('GateID')
        self.GateName = kwargs.get('GateName')
        self.VehicleType = kwargs.get('VehicleType')
        self.CamAddr = kwargs.get('CamAddr')
        self.WebPort = kwargs.get('WebPort')
        self.SDKPort = kwargs.get('SDKPort')
        self.UserName = kwargs.get('UserName')
        self.Password = kwargs.get('Password')
        # 继承
        self.GateType = kwargs.get('GateType')
        # 事件
        self.LicensePlate = ""
        self.LicensePlateImg = ""
        self.GateTime = ""
        self.logger = create_logger(f"logs/camera/{self.CamAddr}.log", self.CamAddr)
        self.Online = False
        self.Debug = True
        # 测试参数
        self.__demo_image_path = "project/service/demo/images"
        self.__demo_image_static_path = "project/static/images/licenseplate"

    def snapshot(self):
        """
        状态快照
        """
        return {
            "CameraID": self.CameraID,
            "GateID": self.GateID,
            "GateName": self.GateName,
            "GateType": self.GateType,
            "VehicleType": self.VehicleType,
            "LicensePlate": self.LicensePlate,
            "LicensePlateImg": self.LicensePlateImg,
            "GateTime": self.GateTime,
        }

    def save_licenseplate_image(self, img_buffer):
        """
        保存图片
        """
        now = datetime.now()
        img_folder = f"{self.__demo_image_static_path}/{self.GateType}/{self.GateName}"
        daily_folder = now.strftime("%Y%m%d")
        folder_name = f"{img_folder}/{daily_folder}"
        # 创建文件夹
        if not os.path.isdir(folder_name):
            os.makedirs(folder_name)
        image_path = f"{folder_name}/{self.LicensePlate}_{now.strftime('%Y%m%d%H%M%S')}.jpg"
        with open(file=image_path, mode="wb") as f:
            f.write(img_buffer)
        # 刷新识别图片及时间
        self.LicensePlateImg = image_path.replace("project/static/","")
        self.GateTime = now.strftime('%Y/%m/%d %H:%M:%S')

    def licenseplate_image_trigger(self):
        """
        识别触发
        """
        try:
            # 选中图片
            img_path = f"{self.__demo_image_path}/{self.VehicleType}"
            img = choice(os.listdir(img_path))
            with open(f"{img_path}/{img}", mode="rb") as f:
                img_buffer = f.read()
            if choice(range(10)):
                self.LicensePlate = img.split(".")[0]
            else:
                self.LicensePlate = "UNKNOWN"
            # 保存图片
            self.save_licenseplate_image(img_buffer)
            self.logger.debug(f"车牌识别结果 => {self.LicensePlate}")
            CameraQ.put(self.snapshot())
        except Exception as e:
            self.logger.error(f"识别错误！原因：{e}")

    def connect(self):
        """
        连接相机
        """
        for i in (self.UserName, self.Password):
            if i in ("", None):
                self.logger.error(f"连接失败！用户名：{self.UserName} 密码：{self.Password}")
                return 0
        self.Online = True
        self.logger.debug(f"连接成功：{self.CamAddr}")

    def disconnect(self):
        """
        断开连接
        """
        self.logger.debug(f"断开连接：{self.CamAddr}")

    def listen(self):
        """
        监听相机
        """
        self.logger.debug(f"开始监听：{self.CamAddr}")

    def service_init(self):
        """
        相机初始化
        """
        self.connect()
        if self.Online:
            self.listen()
